package com.ruiyi.subway.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

/**
 * Created by zhangruiqian on 16/10/21.
 */
@Service
public class MailService {
    @Value("${smtp.host}")
    private String SMTP_HOST;
    @Value("${smtp.port}")
    private int SMTP_PORT;
    @Value("${smtp.user}")
    private String SMTP_USER;
    @Value("${smtp.pass}")
    private String SMTP_PASS;
    @Value("${smtp.personal}")
    private String SMTP_PERSONAL;
    @Value("${smtp.user.cn.name}")
    private String SMTP_USER_CN_NAME;

    public void sendSmtpMail(String receiver, String subject, String content) throws MessagingException, UnsupportedEncodingException {
        final Properties props = new Properties();
        // 表示SMTP发送邮件，需要进行身份验证
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", SMTP_HOST);
        props.put("mail.smtp.port", SMTP_PORT);

        if (SMTP_PORT == 465){
            // 如果使用ssl，则去掉使用25端口的配置，进行如下配置,
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.socketFactory.port", 465);
            props.put("mail.smtp.port", 465);
        }

        // 发件人的账号
        props.put("mail.user", SMTP_USER);
        // 访问SMTP服务时需要提供的密码
        props.put("mail.password", SMTP_PASS);
        // 构建授权信息，用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用环境属性和授权信息，创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        // 创建邮件消息
        MimeMessage message = new MimeMessage(mailSession);
        // 设置发件人
        InternetAddress form = new InternetAddress(props.getProperty("mail.user"));
        form.setPersonal(new String(SMTP_PERSONAL.getBytes("ISO-8859-1"),"utf-8"));
        message.setFrom(form);
        // 设置收件人
        InternetAddress to = new InternetAddress(receiver);
        message.setRecipient(MimeMessage.RecipientType.TO, to);
        // 设置邮件标题
        message.setSubject(subject);
        // 设置邮件的内容体
        message.setContent(content, "text/html;charset=UTF-8");
        // 发送邮件
        Transport.send(message);
    }
}
